package com.demo.controller;

import com.demo.common.Result;
import com.demo.pojo.entity.Classroom;
import com.demo.pojo.dto.ClassroomListDTO;
import com.demo.service.ClassroomService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 教室管理控制器
 */
@RestController
@RequestMapping("/classroom")
@CrossOrigin
public class ClassroomController {
    
    @Autowired
    private ClassroomService classroomService;
    
    /**
     * 获取教室列表
     */
    @GetMapping("/list")
    public Result<List<ClassroomListDTO>> getClassroomList() {
        try {
            List<ClassroomListDTO> list = classroomService.getClassroomList();
            return Result.success(list);
        } catch (Exception e) {
            return Result.error("获取教室列表失败：" + e.getMessage());
        }
    }

    /**
     * 分页获取教室列表
     */
    @GetMapping("/page")
    public Result<Map<String, Object>> getClassroomPage(@RequestParam(defaultValue = "1") int page,
                                                        @RequestParam(defaultValue = "10") int pageSize,
                                                        @RequestParam(required = false) String classroomNo,
                                                        @RequestParam(required = false) String classroomName,
                                                        @RequestParam(required = false) String classroomType,
                                                        @RequestParam(required = false) String building,
                                                        @RequestParam(required = false) Integer status) {
        try {
            Page<Classroom> p = new Page<>(page, pageSize);
            QueryWrapper<Classroom> queryWrapper = new QueryWrapper<>();
            
            // 添加查询条件
            if (classroomNo != null && !classroomNo.isEmpty()) {
                queryWrapper.like("classroom_no", classroomNo);
            }
            if (classroomName != null && !classroomName.isEmpty()) {
                queryWrapper.like("classroom_name", classroomName);
            }
            if (classroomType != null && !classroomType.isEmpty()) {
                queryWrapper.eq("classroom_type", classroomType);
            }
            if (building != null && !building.isEmpty()) {
                queryWrapper.like("building", building);
            }
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            queryWrapper.orderByDesc("classroom_id");
            Page<Classroom> result = classroomService.page(p, queryWrapper);
            
            Map<String, Object> data = new HashMap<>();
            data.put("records", result.getRecords());
            data.put("total", result.getTotal());
            data.put("current", result.getCurrent());
            data.put("size", result.getSize());
            data.put("pages", result.getPages());
            
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("分页获取教室列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID获取教室详情
     */
    @GetMapping("/{id}")
    public Result<Classroom> getClassroomById(@PathVariable Long id) {
        try {
            Classroom classroom = classroomService.getById(id);
            if (classroom != null) {
                return Result.success(classroom);
            } else {
                return Result.error("教室不存在");
            }
        } catch (Exception e) {
            return Result.error("获取教室详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加教室
     */
    @PostMapping("/add")
    public Result<String> addClassroom(@RequestBody Classroom classroom) {
        try {
            // 检查教室编号是否已存在
            QueryWrapper<Classroom> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("classroom_no", classroom.getClassroomNo());
            Classroom existingClassroom = classroomService.getOne(queryWrapper);
            if (existingClassroom != null) {
                return Result.error("教室编号已存在");
            }
            
            classroomService.save(classroom);
            return Result.success("添加教室成功");
        } catch (Exception e) {
            return Result.error("添加教室失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新教室
     */
    @PutMapping("/update")
    public Result<String> updateClassroom(@RequestBody Classroom classroom) {
        try {
            // 检查教室编号是否与其他教室冲突
            QueryWrapper<Classroom> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("classroom_no", classroom.getClassroomNo());
            queryWrapper.ne("classroom_id", classroom.getClassroomId());
            Classroom existingClassroom = classroomService.getOne(queryWrapper);
            if (existingClassroom != null) {
                return Result.error("教室编号已存在");
            }
            
            classroomService.updateById(classroom);
            return Result.success("更新教室成功");
        } catch (Exception e) {
            return Result.error("更新教室失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除教室
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteClassroom(@PathVariable Long id) {
        try {
            // 检查教室是否被使用（这里可以添加更复杂的检查逻辑）
            classroomService.removeById(id);
            return Result.success("删除教室成功");
        } catch (Exception e) {
            return Result.error("删除教室失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除教室
     */
    @DeleteMapping("/batch-delete")
    public Result<String> batchDeleteClassrooms(@RequestBody List<Long> ids) {
        try {
            classroomService.removeByIds(ids);
            return Result.success("批量删除教室成功");
        } catch (Exception e) {
            return Result.error("批量删除教室失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新教室状态
     */
    @PutMapping("/update-status/{id}")
    public Result<String> updateClassroomStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            Classroom classroom = classroomService.getById(id);
            if (classroom == null) {
                return Result.error("教室不存在");
            }
            
            classroom.setStatus(status);
            classroomService.updateById(classroom);
            return Result.success("更新教室状态成功");
        } catch (Exception e) {
            return Result.error("更新教室状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教室类型列表
     */
    @GetMapping("/types")
    public Result<List<String>> getClassroomTypes() {
        try {
            QueryWrapper<Classroom> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT classroom_type");
            List<Classroom> classrooms = classroomService.list(queryWrapper);
            List<String> types = classrooms.stream()
                    .map(Classroom::getClassroomType)
                    .filter(type -> type != null && !type.isEmpty())
                    .distinct()
                    .toList();
            return Result.success(types);
        } catch (Exception e) {
            return Result.error("获取教室类型失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取楼栋列表
     */
    @GetMapping("/buildings")
    public Result<List<String>> getBuildings() {
        try {
            QueryWrapper<Classroom> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT building");
            List<Classroom> classrooms = classroomService.list(queryWrapper);
            List<String> buildings = classrooms.stream()
                    .map(Classroom::getBuilding)
                    .filter(building -> building != null && !building.isEmpty())
                    .distinct()
                    .toList();
            return Result.success(buildings);
        } catch (Exception e) {
            return Result.error("获取楼栋列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据类型获取可用教室
     */
    @GetMapping("/available/{classroomType}")
    public Result<List<Classroom>> getAvailableClassroomsByType(@PathVariable String classroomType) {
        try {
            List<Classroom> classrooms = classroomService.getAvailableClassroomsByType(classroomType);
            return Result.success(classrooms);
        } catch (Exception e) {
            return Result.error("获取可用教室失败：" + e.getMessage());
        }
    }
}